﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gollie.DataTables;

namespace Gollie.Controls
{
	public partial class MyVendorUsers : AuthenticationRequiredAdministratorBaseUserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		protected override void OnPostBack(object sender, EventArgs e)
		{
		}

		protected override void OnFirstHit(object sender, EventArgs e)
		{
			this.fldId.Value = this.UserInfo.Id.ToString();
			this.fldToken.Value = this.UserInfo.WebToken;

			this.Refresh();
		}

		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			switch (e.CommandName)
			{
				case "DeleteRow":
					string[] arg = e.CommandArgument.ToString().Split('|');
					int userId = Convert.ToInt32(arg[0]);
					int rowIndex = Convert.ToInt32(arg[1]);
					this.DeleteRow(userId, rowIndex);
					break;
			}
		}

		private void DeleteRow(int userId, int rowIndex)
		{
			long rowsAffected = Database.Queries.DeregisterUser((uint)userId);

			this.Refresh();
		}

		private void Refresh()
		{
			VendorUsers users = new VendorUsers(this.UserInfo.VendorId);
			this.GridView1.DataSource = users;
			this.GridView1.DataBind();
		}

		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				int userId = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
				if (userId == this.UserInfo.Id)
				{
					e.Row.Cells[0].Controls.Clear();
					foreach (TableCell cell in e.Row.Cells)
					{
						cell.ForeColor = System.Drawing.Color.FromArgb(240, 240, 240);
						cell.BackColor = System.Drawing.Color.FromArgb(200, 200, 200);
					}
				}
			}
		}

		protected SortDirection SortDir
		{
			get
			{
				if (ViewState["dirState"] == null)
					ViewState["dirState"] = SortDirection.Ascending;

				return (SortDirection)ViewState["dirState"];
			}
			set
			{
				ViewState["dirState"] = value;
			}
		}

		protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
		{
			SortDir = SortDir == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
			this.GridView1.DataSource = new VendorUsers(this.UserInfo.VendorId).Sort(e.SortExpression, SortDir == SortDirection.Ascending);
			this.GridView1.DataBind();
		}
	}
}